package com.jack.blog.jedis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class JedisUtil {
    @Autowired
    private JedisPool jedisPool;

    private ThreadLocal<Jedis> jedisThreadLocal=new ThreadLocal<Jedis>(){
        @Override
        protected Jedis initialValue() {
            return jedisPool.getResource();
        }
    };

    public Jedis getJedis(){
        return jedisThreadLocal.get();
    }

    protected void closeJedis(){
        Jedis jedis = jedisThreadLocal.get();
        if (jedis!=null){
            jedisPool.returnResource(jedis);
            jedisThreadLocal.remove();
        }
    }
}
